package com.hns.license.verify;

import java.io.File;
import java.util.prefs.Preferences;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hns.license.LicenseManager;
import com.hns.tool.pub.UtilConfig;

import de.schlichtherle.license.CipherParam;
import de.schlichtherle.license.DefaultCipherParam;
import de.schlichtherle.license.DefaultKeyStoreParam;
import de.schlichtherle.license.DefaultLicenseParam;
import de.schlichtherle.license.KeyStoreParam;
import de.schlichtherle.license.LicenseParam;



/**
 * 验证LICENSEY有效性
 * @author:yecb
 * @email:lps00@163.com
 * @version Revision 2.0.0
 */

public class VerifyLicense {
	private static final Logger logger = LoggerFactory.getLogger(VerifyLicense.class);
	//common param
	private static String PUBLICALIAS = "";
	private static String STOREPWD = "";
	private static String SUBJECT = "";
	private static String licPath = "";
	private static String pubPath = "";
	
	public VerifyLicense(String propertiesPath) {
		
		PUBLICALIAS = UtilConfig.getString("PUBLICALIAS");
		STOREPWD = UtilConfig.getString("STOREPWD");
		SUBJECT = UtilConfig.getString("SUBJECT");
		licPath = propertiesPath+"\\"+UtilConfig.getString("licPath");
		pubPath =propertiesPath+"\\"+UtilConfig.getString("pubPath");
	}

	public boolean verify() {	
		/************** 证书使用者端执行 ******************/

		LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParams());
		// 安装证书
		try {
			licenseManager.install(new File(licPath));
			logger.info("客户端安装证书成功!");
		} catch (Exception e) {
			logger.error("客户端证书安装失败!",e);
			return false;
		}
		// 验证证书
		try {
			licenseManager.verify();
			logger.info("客户端验证证书成功!");
		} catch (Exception e) {
			logger.error("客户端证书验证失效!",e);
			return false;
		}
		return true;
	}

	/**
	 * 返回验证证书需要的参数
	 * @return
	 * @author:yecb
	 * @email:lps00@163.com
	 */
	private static LicenseParam initLicenseParams() {
		Preferences preference = Preferences.userNodeForPackage(VerifyLicense.class);
		CipherParam cipherParam = new DefaultCipherParam(STOREPWD);
		KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(VerifyLicense.class, pubPath, PUBLICALIAS, STOREPWD, null);
		LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT,preference, privateStoreParam, cipherParam);
		return licenseParams;
	}
}